package com.zlsy.secondtime.jmm;


import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhouliang
 * @date 2020/6/10 8:37
 */
public class NoVolatile1 implements Runnable {

    volatile boolean a = false;
    volatile boolean b = false;
    AtomicInteger atomicInteger = new AtomicInteger(0);

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            setDone();
            atomicInteger.incrementAndGet();
        }
    }

    private void setDone() {
        //volatile对于直接赋值的操作是能保证线程安全的，因为赋值本身就是一个原子的操作，加上volatile保证了可见性，所以能保证线程安全
        a = true;
        //volatile不能保证这种形式的线程安全，因为b不再是简单的赋值了，还依赖b之前的状态，不能保证原子操作，所以
        //b得出的结果可能是true也可能是false.
        b = !b;
    }

    public static void main(String[] args) throws InterruptedException {
        NoVolatile1 noVolatile = new NoVolatile1();
        Thread thread1 = new Thread(noVolatile);
        Thread thread2 = new Thread(noVolatile);
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println(noVolatile.a);
        System.out.println(noVolatile.b);
        System.out.println("真正运行次数：" + noVolatile.atomicInteger.get());
    }

}
